//
//  EditViewController.m
//  DIYCoupon
//
//  Created by 张睿 on 16/12/29.
//  Copyright © 2016年 张睿. All rights reserved.
//

#import "EditViewController.h"
#import <Masonry.h>
#import "UIImage+UIImageExt.h"
#import "ImageUtil.h"
#import "ColorMatrix.h"
#import "PreViewController.h"
#import "UIView+SizeExt.h"
#import "WXApiObject.h"
#import "WXApi.h"
#import "MarkingViewController.h"
#import "UILabel+LabelHeightAndWidth.h"


#define SCREEN6_SCALE ([UIScreen mainScreen].bounds.size.width /375)
#define SCREEN6P_SCALE ([UIScreen mainScreen].bounds.size.width /414)
#define PTSCALE ([UIScreen mainScreen].bounds.size.width /1080)

@interface EditViewController ()<WXApiDelegate>

@property (nonatomic, weak)UIView * backGroundView;
@property (nonatomic, weak)UIImageView * editImageView;
@property (nonatomic, weak)UIImageView * bottomImageView;
@property (nonatomic, weak)UIButton * shareButton;
@property (nonatomic, weak)UIButton * specialButton;
@property (nonatomic, weak)UIButton * tabButton;
@property (nonatomic, weak)UIButton * frameButton;
//边框滑动栏
@property (nonatomic, weak)UIScrollView * framesScroll;
//边框图
@property (nonatomic, strong)UIImageView *frameView;
//特效滑动栏
@property (nonatomic, weak)UIScrollView * effectScroll;
//特效编辑图片
@property (nonatomic, strong)UIImage * editSpecialImage;
//标签说明
@property (nonatomic, weak)UILabel * tabLabel;

@property (nonatomic, weak)UITextField * textField;

@property (nonatomic, assign) BOOL keyBoardlsVisible;

@property (nonatomic, strong)UIImageView * imageByPinch;

@property (nonatomic, strong)UIImageView * shareImage;

@property (nonatomic, strong)PreViewController * preViewVC;

@property (nonatomic, strong)UILabel * tabLabelInImg;

@property (nonatomic, strong)UIButton * deleteBtn;

@property (nonatomic, strong)UIImageView * showImage;

@end

@implementation EditViewController{
    
    float f;
    CGSize size;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"EditView";
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.view.userInteractionEnabled = YES;
    _keyBoardlsVisible = NO;
    
    self.view.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hiddenScroolVeiw)];
    [self.view addGestureRecognizer:tapGesture];
    
    [self setupBarButton];
    [self setupUI];
}

#pragma mark - 点击空白处隐藏边框,特效scrollview -
- (void)hiddenScroolVeiw{
    
    self.effectScroll.hidden = YES;
    self.framesScroll.hidden = YES;
    self.tabLabel.hidden = YES;
}

#pragma mark - 创建barButton -
- (void)setupBarButton{
    UIBarButtonItem * backItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(popToHomeView)];
    
    self.navigationItem.leftBarButtonItem = backItem;
    
    UIBarButtonItem * previewItem = [[UIBarButtonItem alloc] initWithTitle:@"预览" style:UIBarButtonItemStylePlain target:self action:@selector(previewEditImage)];
    
    self.navigationItem.rightBarButtonItem = previewItem;
}

#pragma mark - 取消选择,返回首页 -
- (void)popToHomeView{
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 预览 -
- (void)previewEditImage{
    
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    self.preViewVC = [[PreViewController alloc] initWithFrame:self.view.bounds];
    
//    UIGraphicsBeginImageContext(self.editImageView.bounds.size);
    UIGraphicsBeginImageContextWithOptions(self.backGroundView.bounds.size,YES,0);
    [self.backGroundView.layer renderInContext:UIGraphicsGetCurrentContext()];
    
    UIImage *image=UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    self.preViewVC.preImage = image;
    
    UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hiddenPreView)];
    
    [self.preViewVC addGestureRecognizer:tapGesture];
    
    [self.view addSubview:self.preViewVC];
    
}

#pragma mark - 预览遮罩的点击效果 -
- (void)hiddenPreView{
    
    self.preViewVC.hidden = YES;
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)setupUI{
    //背景View
    UIView * backGroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0 * SCREEN6P_SCALE, 414 * SCREEN6P_SCALE, 450 * SCREEN6P_SCALE)];
    backGroundView.backgroundColor = [UIColor blackColor];
    backGroundView.userInteractionEnabled = YES;
    backGroundView.clipsToBounds = YES;
    
    self.backGroundView = backGroundView;
    
    [self.view addSubview:backGroundView];
    //编辑的图片
    UIImageView * editImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 414, 450)];
    [editImage setContentMode:UIViewContentModeScaleAspectFill];
    editImage.image = self.editImage;
    self.editSpecialImage = self.editImage;
    editImage.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(addTabMarking:)];
    
    [editImage addGestureRecognizer:tapGesture];
    
    UIPinchGestureRecognizer* pinchGR = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchAction:)];

    [editImage addGestureRecognizer:pinchGR];
    
    UIPanGestureRecognizer *panGP = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panActionOfEditImage:)];
    
    [editImage addGestureRecognizer:panGP];
    
    UIRotationGestureRecognizer* rotaGR = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotaAction:)];
    
    [editImage addGestureRecognizer:rotaGR];
    
    self.editImageView = editImage;
    
    [self.backGroundView addSubview:self.editImageView];


    //底部边框
    UIImageView * bottomImg = [[UIImageView alloc] init];
    bottomImg.backgroundColor = [UIColor lightGrayColor];
    
    self.bottomImageView = bottomImg;
    
    [self.view addSubview:self.bottomImageView];
    
    //发布按钮
    UIButton * shareBtn = [[UIButton alloc] init];
    [shareBtn setTitle:@"发布" forState:UIControlStateNormal];
    [shareBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [shareBtn setBackgroundColor:[UIColor redColor]];
    [shareBtn addTarget:self action:@selector(shareToFriends) forControlEvents:UIControlEventTouchUpInside];
    self.shareButton = shareBtn;
    
    [self.view addSubview:self.shareButton];
    
    //特效按钮
    UIButton * specialBtn = [[UIButton alloc] init];
    [specialBtn setTitle:@"特效" forState:UIControlStateNormal];
    [specialBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [specialBtn addTarget:self action:@selector(specialImage:) forControlEvents:UIControlEventTouchUpInside];
    self.specialButton = specialBtn;
    
    [self.view addSubview:self.specialButton];
    //标签按钮
    UIButton * tagBtn = [[UIButton alloc] init];
    [tagBtn setTitle:@"标签" forState:UIControlStateNormal];
    [tagBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [tagBtn addTarget:self action:@selector(tabImage:) forControlEvents:UIControlEventTouchUpInside];
    
    self.tabButton = tagBtn;
    
    [self.view addSubview:self.tabButton];
    //边框按钮
    UIButton * frameBtn = [[UIButton alloc] init];
    [frameBtn setTitle:@"边框" forState:UIControlStateNormal];
    [frameBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [frameBtn addTarget:self action:@selector(frameImage:) forControlEvents:UIControlEventTouchUpInside];
    
    self.frameButton = frameBtn;
    
    [self.view addSubview:self.frameButton];
    //边框滑动栏
    UIScrollView * frameScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 450 * SCREEN6P_SCALE, 375 * SCREEN6_SCALE, 155 * SCREEN6P_SCALE)];
    frameScrollView.showsVerticalScrollIndicator = NO;
    frameScrollView.showsHorizontalScrollIndicator = NO;
    frameScrollView.userInteractionEnabled = YES;
    frameScrollView.hidden = YES;
    frameScrollView.bounces = NO;
    [frameScrollView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"pe_bg_one.png"]]];
//    [frameScrollView setBackgroundColor:[UIColor whiteColor]];
    
    for (int i = 0; i < 5; i++) {
        UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(i * 115 * SCREEN6P_SCALE, 15 * SCREEN6P_SCALE, 104 * SCREEN6P_SCALE, 120 * SCREEN6P_SCALE)];
        imageView.image=[UIImage imageNamed:[NSString stringWithFormat:@"border_%d.png",i]];
        imageView.tag=i;
        imageView.userInteractionEnabled=YES;
        UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGuestAction:)];
        [imageView addGestureRecognizer:tapGesture];
        tapGesture.numberOfTapsRequired=1;
        tapGesture.numberOfTouchesRequired=1;
        [frameScrollView addSubview:imageView];
    }
    [frameScrollView setContentSize:CGSizeMake(23*52,70)];
    
    self.framesScroll = frameScrollView;
    
    [self.view addSubview:frameScrollView];
    //边框图
    self.frameView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 55 * SCREEN6_SCALE, 375 * SCREEN6_SCALE, 500 * SCREEN6_SCALE)];
    
    //特效滑动栏
    UIScrollView * effectView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 450 * SCREEN6P_SCALE, 375 * SCREEN6_SCALE, 155 * SCREEN6P_SCALE)];
    effectView.userInteractionEnabled=YES;
    
//    [effectView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"pe_bg_one.png"]]];
    [effectView setBackgroundColor:[UIColor whiteColor]];
    effectView.hidden = YES;
    
    //构建effectScroll上的小视图
    NSArray *arr = [NSArray arrayWithObjects:@"原图",@"川菜",@"火锅",@"粤菜",@"烧烤",@"海鲜",@"甜品",@"西餐",@"日料",@"浪漫",@"光晕",@"蓝调",@"梦幻",@"夜色", nil];
    effectView.indicatorStyle=UIScrollViewIndicatorStyleBlack;
    effectView.showsHorizontalScrollIndicator=NO;
    effectView.showsVerticalScrollIndicator=NO;
    effectView.bounces=NO;
    float x = 0.0;
    size=CGSizeMake(104 * SCREEN6P_SCALE, 120 * SCREEN6P_SCALE);
    for (int i = 0; i < 14; i++) {
        x = 10 + 110 * SCREEN6P_SCALE *i;
        UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(setImageStyle:)];
        recognizer.numberOfTouchesRequired = 1;
        recognizer.numberOfTapsRequired = 1;
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(x, 130 * SCREEN6P_SCALE, 104 * SCREEN6P_SCALE, 30)];
        [label setBackgroundColor:[UIColor clearColor]];
        [label setText:[arr objectAtIndex:i]];
        [label setTextAlignment:NSTextAlignmentCenter];
        [label setFont:[UIFont systemFontOfSize:17.0f]];
        [label setTextColor:[UIColor blackColor]];
        [label setTag:i];
        [label addGestureRecognizer:recognizer];
        [effectView addSubview:label];
        
        
        UIImageView *bgImageView = [[UIImageView alloc]initWithFrame:CGRectMake(x, 10, 104 * SCREEN6P_SCALE, 120 * SCREEN6P_SCALE)];
        [bgImageView setTag:i];
        [bgImageView addGestureRecognizer:recognizer];
        [bgImageView setUserInteractionEnabled:YES];
        UIImage *bgImage = [self changeImage:i isOrginalImage:NO];
        bgImageView.image = bgImage;
        [effectView addSubview:bgImageView];
    }
    effectView.contentSize = CGSizeMake(x + 104 * SCREEN6P_SCALE, 150 * SCREEN6P_SCALE);
    
    self.effectScroll = effectView;
    
    [self.view addSubview:self.effectScroll];
    
    //标签说明
    UILabel * markingLabel = [[UILabel alloc] init];
    markingLabel.text = @"点击图片添加文字";
    markingLabel.textColor = [UIColor grayColor];
    markingLabel.textAlignment = NSTextAlignmentCenter;
    markingLabel.font = [UIFont systemFontOfSize:17];
    markingLabel.hidden = YES;
    
    self.tabLabel = markingLabel;
    
    [self.view addSubview:self.tabLabel];
}

#pragma mark - 页面布局 -
- (void)viewDidLayoutSubviews{
    
    [super viewDidLayoutSubviews];
    //添加图片按钮
//    [self.editImageView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.leading.trailing.mas_equalTo(self.view);
//        make.height.mas_equalTo(400 * SCREEN6_SCALE);
//    }];
    //底部边框
    [self.bottomImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.view);
        make.height.mas_equalTo(1 * SCREEN6_SCALE);
        make.bottom.mas_equalTo(self.view).offset(-60 * SCREEN6_SCALE);
    }];
    //发布按钮
    [self.shareButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.trailing.mas_equalTo(self.view);
        make.top.mas_equalTo(self.bottomImageView);
        make.width.mas_equalTo(135 * SCREEN6_SCALE);
    }];
    //特效按钮
    [self.specialButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.shareButton.mas_centerY);
//        make.bottom.mas_equalTo(self.shareButton.mas_bottom).offset(-5);
        make.trailing.mas_equalTo(self.shareButton.mas_leading).offset(-40 * SCREEN6P_SCALE);
    }];
    //标签按钮
    [self.tabButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.specialButton.mas_centerY);
        make.trailing.mas_equalTo(self.specialButton.mas_leading).offset(-40  * SCREEN6P_SCALE);
    }];
    //边框按钮
    [self.frameButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.tabButton.mas_centerY);
        make.trailing.mas_equalTo(self.tabButton.mas_leading).offset(-40  * SCREEN6P_SCALE);
    }];
    //边框滑动栏
//    [self.framesScroll mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.leading.trailing.mas_equalTo(self.view);
//        make.top.mas_equalTo(self.editImageView.mas_bottom).offset(15);
//        make.bottom.mas_equalTo(self.view).offset(-15);
//        make.width.mas_equalTo(414 * SCREEN6P_SCALE);
//        
//    }];
    
    //
    [self.tabLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.top.mas_equalTo(self.editImageView.mas_bottom).offset(65 * SCREEN6P_SCALE);
    }];
}

#pragma mark - 分享到朋友圈 -
- (void)shareToFriends{
    CGFloat x;
    CGFloat y;
    CGFloat width;
    CGFloat height;
    
        self.shareImage = [[UIImageView alloc] init];
    if (self.editImageView.hidden) {
        x = self.frameView.frame.origin.x;
        y = self.frameView.frame.origin.y;
        width = self.frameView.bounds.size.width;
        height = self.frameView.bounds.size.height + 100 * SCREEN6P_SCALE;
    }else{
        x = self.editImageView.frame.origin.x;
        y = self.editImageView.frame.origin.y;
        width = self.editImageView.bounds.size.width;
        height = self.editImageView.bounds.size.height + 100 * SCREEN6P_SCALE;
    }
    
        
        self.shareImage.frame = CGRectMake(x, y, width, height);
        [self.view addSubview:self.shareImage];
    
        UIImageView * imageOfEd = [[UIImageView alloc] init];
        CGSize sizeimageOfEd = CGSizeMake(width, height - 100 * SCREEN6P_SCALE);
    
        UIGraphicsBeginImageContextWithOptions(sizeimageOfEd,YES,0);
    
    if (self.editImageView.hidden) {
        [self.frameView.layer renderInContext:UIGraphicsGetCurrentContext()];
    }else{
        [self.editImageView.layer renderInContext:UIGraphicsGetCurrentContext()];
    }
    
        UIImage *image=UIGraphicsGetImageFromCurrentImageContext();
        
        UIGraphicsEndImageContext();
        
        imageOfEd.image = image;
        
        [self.shareImage addSubview:imageOfEd];
        
        [imageOfEd mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.leading.trailing.mas_equalTo(self.shareImage);
            make.height.mas_equalTo(self.editImageView.bounds.size.height);
        }];
        
        UIImageView * bottomImage = [[UIImageView alloc] init];
        bottomImage.backgroundColor = [UIColor whiteColor];
        
        [self.shareImage addSubview:bottomImage];
        
        [bottomImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.trailing.bottom.mas_equalTo(self.shareImage);
            make.height.mas_equalTo(100 * SCREEN6P_SCALE);
        }];
        
        UILabel * fontLabel = [[UILabel alloc] init];
        fontLabel.textColor = [UIColor blackColor];
        fontLabel.text = @"锅德海鲜火锅(淮海西路点)";//width / 100 * 4
        fontLabel.font = [UIFont systemFontOfSize:30 * PTSCALE];
        
        [bottomImage addSubview:fontLabel];
        
        [fontLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(imageOfEd.mas_bottom).offset(5 * SCREEN6P_SCALE);
            make.trailing.mas_equalTo(bottomImage.mas_trailing).offset(-80 * SCREEN6P_SCALE);
            make.leading.mas_equalTo(bottomImage).offset(5 * SCREEN6P_SCALE);
        }];
        
        UILabel * bottomLabel = [[UILabel alloc] init];
        bottomLabel.textColor = [UIColor blackColor];
        bottomLabel.text = @"长按图片识别二维码获取优惠";
        bottomLabel.font = [UIFont systemFontOfSize:30 * PTSCALE];
        
        [bottomImage addSubview:bottomLabel];
        
        [bottomLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(fontLabel.mas_bottom).offset(5);
            make.trailing.mas_equalTo(fontLabel);
            make.leading.mas_equalTo(fontLabel);
        }];
        
        UIImageView * markCardImage = [[UIImageView alloc] init];
        markCardImage.image = [UIImage imageNamed:@"QRcode"];
        
        [bottomImage addSubview:markCardImage];
        
        [markCardImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(fontLabel);
            make.bottom.mas_equalTo(bottomLabel);
            make.trailing.mas_equalTo(bottomImage.mas_trailing).offset(-5 * SCREEN6P_SCALE);
            make.width.mas_equalTo(16 * SCREEN6P_SCALE * width / 100 * SCREEN6P_SCALE);
        }];
    
    CGSize sizeTest = CGSizeMake(width, height);
//    UIGraphicsBeginImageContext(sizeTest);
    UIGraphicsBeginImageContextWithOptions(sizeTest,YES,0);
    
    [self.shareImage.layer renderInContext:UIGraphicsGetCurrentContext()];
    
    UIImage * showImage=UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    //    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    
    WXMediaMessage *message = [WXMediaMessage message];
    
    WXImageObject * imageObject = [WXImageObject object];

//    imageObject.imageData = [self imageWithImage:image scaledToSize:sizeTest];
    NSData * data = UIImageJPEGRepresentation(showImage, 1.0);
//    NSData * data = UIImageJPEGRepresentation(self.editImageView.image, 1.0);
    imageObject.imageData = data;
    message.mediaObject = imageObject;
    
    SendMessageToWXReq * req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = WXSceneTimeline;
    [WXApi sendReq:req];
    
}

- (NSData *)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize;
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return UIImageJPEGRepresentation(newImage, 1.0);
}

#pragma mark - 特效 -
- (void)specialImage:(UIButton *)button{
    [self.frameButton setSelected:NO];
    [self.tabButton setSelected:NO];
    self.framesScroll.hidden = YES;
    self.tabLabel.hidden = YES;
    
    if(button.selected==NO){
        [button setSelected:YES];
        self.effectScroll.hidden = NO;
    }
    else{
        [button setSelected:NO];
        self.effectScroll.hidden = YES;
    }
}
#pragma mark - 标签 -
- (void)tabImage:(UIButton *)button{
    
    [self.specialButton setSelected:NO];
    [self.frameButton setSelected:NO];
    self.effectScroll.hidden = YES;
    self.framesScroll.hidden = YES;
    
    if(button.selected==NO){
        [button setSelected:YES];
        self.tabLabel.hidden = NO;
    }
    else{
        [button setSelected:NO];
        self.tabLabel.hidden = YES;
    }

}

#pragma mark - 边框 -
- (void)frameImage:(UIButton *)button{
    
    [self.specialButton setSelected:NO];
    [self.tabButton setSelected:NO];
    self.effectScroll.hidden = YES;
    self.tabLabel.hidden = YES;
    
    if(button.selected == NO){
        
        [button setSelected:YES];
        self.framesScroll.hidden = NO;
    }else{
        [button setSelected:NO];
        self.framesScroll.hidden = YES;
    }
    
}

#pragma mark - 边框效果点击事件 -
-(void)tapGuestAction:(UITapGestureRecognizer *)sender{
    
    UIGraphicsBeginImageContextWithOptions(self.editImageView.bounds.size,YES,0);
    
    [self.editImageView.layer renderInContext:UIGraphicsGetCurrentContext()];
    
    UIImage * image2=UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    UIView *imageView=sender.view;
    
    if (imageView.tag == 0) {
        self.frameView.hidden = YES;
        self.editImageView.hidden = NO;
        
        UIGraphicsBeginImageContextWithOptions(self.showImage.bounds.size,YES,0);
        [self.showImage.layer renderInContext:UIGraphicsGetCurrentContext()];
        
        UIImage * image1 =UIGraphicsGetImageFromCurrentImageContext();
        
        UIGraphicsEndImageContext();
        self.editImageView.image = image1;
    }else if (imageView.tag == 1) {
        
        [self.frameView removeFromSuperview];
        
        self.editImageView.hidden = YES;
        self.frameView.image=[UIImage imageNamed:[NSString stringWithFormat:@"border_%ld.png",(long)imageView.tag]];
        self.frameView.frame = CGRectMake(20 * SCREEN6P_SCALE, 0, 374 * SCREEN6P_SCALE, 450 * SCREEN6P_SCALE);
        self.frameView.userInteractionEnabled = YES;
        [self.backGroundView addSubview:self.frameView];
        
        
        UIImageView * backImageView = [[UIImageView alloc] init];
        backImageView.image = [UIImage imageNamed:@"y"];
//        backImageView.backgroundColor = [UIColor redColor   ];
        backImageView.userInteractionEnabled = YES;
        backImageView.clipsToBounds = YES;
        backImageView.contentMode = UIViewContentModeScaleToFill;
        [self.frameView addSubview:backImageView];
        //left:48 top:187 bottom:49
        [backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.mas_equalTo(self.frameView).offset(90 * PTSCALE);
            make.top.mas_equalTo(self.frameView).offset(270 * PTSCALE);
            make.trailing.mas_equalTo(self.frameView).offset(-90 * PTSCALE);
            make.bottom.mas_equalTo(self.frameView).offset(-90 * PTSCALE);
        }];
        
        self.showImage = [[UIImageView alloc] init];
//        self.showImage.image = self.editImageView.image;
        self.showImage.image = image2;
        self.showImage.contentMode = UIViewContentModeScaleAspectFill;
        self.showImage.userInteractionEnabled = YES;
        
        [backImageView addSubview:self.showImage];
        
        [self.showImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.leading.trailing.mas_equalTo(backImageView);
        }];
     
        UIPinchGestureRecognizer* pinchGR = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchAction:)];
        [self.showImage addGestureRecognizer:pinchGR];
        
        UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(addTabMarking:)];
        
        [self.showImage addGestureRecognizer:tapGesture];
        
        UIRotationGestureRecognizer* rotaGR = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotaAction:)];
        
        [self.showImage addGestureRecognizer:rotaGR];
        
   }
        else if (imageView.tag == 2) {
            
            [self.frameView removeFromSuperview];
            
            self.editImageView.hidden = YES;
            self.frameView.image=[UIImage imageNamed:@"组6"];
            self.frameView.frame = CGRectMake(20 * SCREEN6P_SCALE, 0, 374 * SCREEN6P_SCALE, 450 * SCREEN6P_SCALE);
            self.frameView.userInteractionEnabled = YES;
            [self.backGroundView addSubview:self.frameView];
            
            
            UIImageView * backImageView = [[UIImageView alloc] init];
            //            backImageView.image = [UIImage imageNamed:@"y"];
            backImageView.backgroundColor = [UIColor whiteColor];
            backImageView.userInteractionEnabled = YES;
            backImageView.clipsToBounds = YES;
            backImageView.contentMode = UIViewContentModeScaleToFill;
            [self.frameView addSubview:backImageView];
            //left:26 top:263 bottom:31
            [backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.leading.mas_equalTo(self.frameView).offset(32 * PTSCALE);
                make.top.mas_equalTo(self.frameView).offset(298 * PTSCALE);
                make.trailing.mas_equalTo(self.frameView).offset(-32 * PTSCALE);
                make.bottom.mas_equalTo(self.frameView).offset(-35 * PTSCALE);
            }];
            
            self.showImage = [[UIImageView alloc] init];
//            self.showImage.image = self.editImageView.image;
            self.showImage.image = image2;
            self.showImage.contentMode = UIViewContentModeScaleAspectFill;
            self.showImage.userInteractionEnabled = YES;
            
            [backImageView addSubview:self.showImage];
            
            [self.showImage mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.bottom.leading.trailing.mas_equalTo(backImageView);
            }];
            
            UIPinchGestureRecognizer* pinchGR = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchAction:)];
            [self.showImage addGestureRecognizer:pinchGR];
            
            UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(addTabMarking:)];
            
            [self.showImage addGestureRecognizer:tapGesture];
            
            UIRotationGestureRecognizer* rotaGR = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotaAction:)];
            
            [self.showImage addGestureRecognizer:rotaGR];   
        
        }
        else if (imageView.tag == 3){
            
            [self.frameView removeFromSuperview];
            
            self.editImageView.hidden = YES;
            self.frameView.image=[UIImage imageNamed:@"bian2"];
            self.frameView.frame = CGRectMake(20 * SCREEN6P_SCALE, 0, 374 * SCREEN6P_SCALE, 450 * SCREEN6P_SCALE);
            self.frameView.userInteractionEnabled = YES;
            [self.backGroundView addSubview:self.frameView];
            
            
            UIImageView * backImageView = [[UIImageView alloc] init];
            //            backImageView.image = [UIImage imageNamed:@"y"];
            backImageView.backgroundColor = [UIColor whiteColor];
            backImageView.userInteractionEnabled = YES;
            backImageView.clipsToBounds = YES;
            backImageView.contentMode = UIViewContentModeScaleToFill;
            [self.frameView addSubview:backImageView];
            //left:26 top:242 bottom:32
            [backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.leading.mas_equalTo(self.frameView).offset(32 * PTSCALE);
                make.top.mas_equalTo(self.frameView).offset(270 * PTSCALE);
                make.trailing.mas_equalTo(self.frameView).offset(-32 * PTSCALE);
                make.bottom.mas_equalTo(self.frameView).offset(-36 * PTSCALE);
            }];
            
            self.showImage = [[UIImageView alloc] init];
//            self.showImage.image = self.editImageView.image;
             self.showImage.image = image2;
            self.showImage.contentMode = UIViewContentModeScaleAspectFill;
            self.showImage.userInteractionEnabled = YES;
            
            [backImageView addSubview:self.showImage];
            
            [self.showImage mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.bottom.leading.trailing.mas_equalTo(backImageView);
            }];
            
            UIImageView * lineImage = [[UIImageView alloc] init];
            lineImage.backgroundColor = [UIColor whiteColor];
            
            [backImageView addSubview:lineImage];
            
            [lineImage mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.bottom.mas_equalTo(backImageView);
                make.width.mas_equalTo(2 * SCREEN6P_SCALE);
                make.leading.mas_equalTo(backImageView).offset(650 * PTSCALE);
            }];
            
            UIPinchGestureRecognizer* pinchGR = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchAction:)];
            [self.showImage addGestureRecognizer:pinchGR];
            
            UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(addTabMarking:)];
            
            [self.showImage addGestureRecognizer:tapGesture];
            
            UIRotationGestureRecognizer* rotaGR = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotaAction:)];
            
            [self.showImage addGestureRecognizer:rotaGR];
        }
        else if (imageView.tag == 4){
            
            UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
            UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
            effectView.frame = self.editImageView.bounds;
            
            self.editImageView.hidden = YES;
            
            self.frameView.image = self.editImageView.image;
            self.frameView.frame = self.editImageView.bounds;
            self.frameView.userInteractionEnabled = YES;
            
            [self.frameView addSubview:effectView];
            [self.backGroundView addSubview:self.frameView];
//            [self.editImageView addSubview:effectView];
            
            UIImageView * backImageView = [[UIImageView alloc] init];
            backImageView.image = [UIImage imageNamed:@"wire"];
            backImageView.userInteractionEnabled = YES;
            backImageView.clipsToBounds = YES;
            backImageView.contentMode = UIViewContentModeScaleToFill;
            [self.frameView addSubview:backImageView];
            //left:125 top:106 bottom:104
            [backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
//                make.leading.mas_equalTo(self.frameView).offset(125 * PTSCALE);
                make.centerX.mas_equalTo(self.frameView.mas_centerX);
                make.width.mas_equalTo(270 * SCREEN6_SCALE);
                make.top.mas_equalTo(self.frameView).offset(106 * PTSCALE);
//                make.trailing.mas_equalTo(self.frameView).offset(-200 * PTSCALE);
                make.bottom.mas_equalTo(self.frameView).offset(-106 * PTSCALE);
            }];
            
            self.showImage = [[UIImageView alloc] init];
//            self.showImage.image = self.editImageView.image;
             self.showImage.image = image2;
            self.showImage.contentMode = UIViewContentModeScaleAspectFit;
            self.showImage.userInteractionEnabled = YES;
            
            [backImageView addSubview:self.showImage];
            
            [self.showImage mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.leading.bottom.trailing.mas_equalTo(backImageView);
            }];
            
            UIPinchGestureRecognizer* pinchGR = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchAction:)];
            [self.showImage addGestureRecognizer:pinchGR];
            
            UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(addTabMarking:)];
            
            [self.showImage addGestureRecognizer:tapGesture];
            
            UIRotationGestureRecognizer* rotaGR = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotaAction:)];
            
            [self.showImage addGestureRecognizer:rotaGR];
        }
        else{
        self.editImageView.hidden = NO;
        [self.frameView removeFromSuperview];
    }
    
}

#pragma mark - 捏合手势的回调方法 -
//编辑图片缩放
- (void)pinchAction:(UIPinchGestureRecognizer*)sender{
    //通过捏合手势的到缩放比率
    float scale = sender.scale;
    //得到该手势所作用的视图
    UIView *view = sender.view;
    //2D仿射变换函数中的缩放函数来实现视图的放大缩小
    
    //是在原有基础上来改变当前的视图
    //函数的第一个参数：现有的视图的transform值
    //第二个参数：x轴上的缩放比率
    //第三个参数:y轴上的缩放比率
    
    //是在视图最初的transform状态上改变，不管执行多少次，都是以该视图最初的transform状态为基础来改变
    view.transform = CGAffineTransformMakeScale(scale, scale);
//    self.frameView.transform = CGAffineTransformIdentity;
//    self.frameView.transform = CGAffineTransformMakeScale(1, 1);
//        view.transform = CGAffineTransformScale(view.transform, scale / 2, scale / 2);
    //每次捏合动作完毕之后，让此捏合值复原，使得它每次都是从100%开始缩放
//    sender.scale = 1;
    
}

#pragma mark - 特效滤镜 -
-(UIImage *)changeImage:(int)index isOrginalImage:(BOOL)isOrginal
{
    UIImage *image;
    
    
    if (isOrginal) {
        
        image=self.editSpecialImage;
    }else{
        
        image =[self.editSpecialImage imageByScalingAndCroppingForSize:size];
        
    }
    
    //NSLog(@"========%d",image.imageOrientation);
    if (image.imageOrientation!=0) {
        image=[self fixOrientation:image];
    }
    switch (index) {
        case 0:
        {
            return image;
        }
            break;
        case 1:
        {
            return [ImageUtil imageWithImage:image withColorMatrix:colormatrix_lomo];
        }
            break;
        case 2:
        {
            return[ImageUtil imageWithImage:image withColorMatrix:colormatrix_heibai];
        }
            break;
        case 3:
        {
            return [ImageUtil imageWithImage:image withColorMatrix:colormatrix_huajiu];
        }
            break;
        case 4:
        {
            return [ImageUtil imageWithImage:image withColorMatrix:colormatrix_gete];
        }
            break;
        case 5:
        {
            return [ImageUtil imageWithImage:image withColorMatrix:colormatrix_ruise];
        }
            break;
        case 6:
        {
            return [ImageUtil imageWithImage:image withColorMatrix:colormatrix_danya];
        }
            break;
        case 7:
        {
            return [ImageUtil imageWithImage:image withColorMatrix:colormatrix_jiuhong];
        }
            break;
        case 8:
        {
            return [ImageUtil imageWithImage:image withColorMatrix:colormatrix_qingning];
        }
            break;
        case 9:
        {
            return [ImageUtil imageWithImage:image withColorMatrix:colormatrix_langman];
        }
            break;
        case 10:
        {
            return [ImageUtil imageWithImage:image withColorMatrix:colormatrix_guangyun];
        }
            break;
        case 11:
        {
            return [ImageUtil imageWithImage:image withColorMatrix:colormatrix_landiao];
            
        }
            break;
        case 12:
        {
            return[ImageUtil imageWithImage:image withColorMatrix:colormatrix_menghuan];
            
        }
            break;
        case 13:
        {
            return [ImageUtil imageWithImage:image withColorMatrix:colormatrix_yese];
            
        }
    }
    return nil;
}

//修正 orientation
- (UIImage *)fixOrientation:(UIImage *)aImage {
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

- (void)setImageStyle:(UITapGestureRecognizer *)sender
{
    //CGSize OringalSize=self.editImage.size;
    UIImage *image =   [self changeImage:sender.view.tag isOrginalImage:YES];
    //    [self.imageView setContentMode:UIViewContentModeScaleAspectFill];
    if (self.editImageView.hidden) {
        self.showImage.image = image;
    }else{
        self.editImageView.image= image;
    }
}

#pragma mark - 添加标签的点击事件 -
- (void)addTabMarking:(UITapGestureRecognizer *)sender{

    if (self.tabButton.selected) {
        MarkingViewController * markingVC = [MarkingViewController new];
        
        [self.navigationController pushViewController:markingVC animated:YES];
        self.tabLabelInImg = [[UILabel alloc] initWithFrame:CGRectMake(200, 200, 100, 24)];
//        self.tabLabelInImg.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"label_bg"]];
        
        self.tabLabelInImg.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"label_backGround"]];
        self.tabLabelInImg.font = [UIFont systemFontOfSize:11];
        //文本文字自适应大小
        //    tabLabel.adjustsFontSizeToFitWidth = YES;
        //超出label边界文字的截取方式
        self.tabLabelInImg.lineBreakMode = NSLineBreakByTruncatingTail;
        self.tabLabelInImg.textColor = [UIColor whiteColor];
        self.tabLabelInImg.userInteractionEnabled = YES;
//        self.tabLabelInImg.tag = 1++;
        
        
        [markingVC returnText:^(NSString *showText) {
            self.tabLabelInImg.text = [NSString stringWithFormat:@"       %@   ",showText];
            CGFloat width = [UILabel getWidthWithTitle:self.tabLabelInImg.text font:self.tabLabelInImg.font];
            if (width < 122) {
                self.tabLabelInImg.frame = CGRectMake(100, 200, width, 20);
            }else{
                self.tabLabelInImg.frame = CGRectMake(100, 200, 122, 20);
            }
            if (self.editImageView.hidden) {
                [self.showImage addSubview:self.tabLabelInImg];
            }else{
                [self.editImageView addSubview:self.tabLabelInImg];
            }
            
            self.tabLabelInImg.tag = self.editImageView.subviews.count;
            //标签添加手势
            UIPanGestureRecognizer *panGP = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
            [self.tabLabelInImg addGestureRecognizer:panGP];
            
            UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(deleteTabLabel:)];
            [self.tabLabelInImg addGestureRecognizer:tapGesture];
            
//            [self.tabButton setSelected:NO];
//            self.tabLabel.hidden = YES;
            
            
        }];
        
    }else{
        
        self.deleteBtn.hidden = YES;
    }
    
}

#pragma mark - 标签拖拽事件 -
- (void)panAction:(UIPanGestureRecognizer*)sender{
    if (self.tabButton.selected) {
        CGPoint translation = [sender translationInView:self.editImageView];
        CGPoint newCenter = CGPointMake(sender.view.center.x+ translation.x,
                                        sender.view.center.y + translation.y);//    限制屏幕范围：
        newCenter.y = MAX(sender.view.frame.size.height/2, newCenter.y);
        newCenter.y = MIN(self.editImageView.frame.size.height - sender.view.frame.size.height/2,  newCenter.y);
        newCenter.x = MAX(sender.view.frame.size.width/2, newCenter.x);
        newCenter.x = MIN(self.editImageView.frame.size.width - sender.view.frame.size.width/2,newCenter.x);
        sender.view.center = newCenter;
        [sender setTranslation:CGPointZero inView:self.view];
    }else{
        return;
    }
    
}

#pragma mark - 编辑图片拖拽事件 -
- (void)panActionOfEditImage:(UIPanGestureRecognizer*)sender{
    
        CGPoint translation = [sender translationInView:self.backGroundView];
        CGPoint newCenter = CGPointMake(sender.view.center.x+ translation.x,
                                        sender.view.center.y + translation.y);//    限制屏幕范围：
        newCenter.y = MAX(sender.view.frame.size.height/2, newCenter.y);
        newCenter.y = MIN(self.backGroundView.frame.size.height - sender.view.frame.size.height/2,  newCenter.y);
        newCenter.x = MAX(sender.view.frame.size.width/2, newCenter.x);
        newCenter.x = MIN(self.backGroundView.frame.size.width - sender.view.frame.size.width/2,newCenter.x);
        sender.view.center = newCenter;
        [sender setTranslation:CGPointZero inView:self.view];

    
}

//旋转手势回调方法
- (void)rotaAction:(UIRotationGestureRecognizer*)sender{
    //通过手势的到旋转角度
//    float rota = sender.rotation;
//    //得到该手势作用的视图
//    UIView *view = sender.view;
//    //通过2D仿射变换函数中的旋转函数来使得当前视图旋转。
//    view.transform = CGAffineTransformRotate(view.transform, rota);
//    //复原
//    //    sender.rotation = 0;
//    sender.rotation = 0;
}

// ⑥shanchu的回调方法
- (void)deleteTabLabel:(UITapGestureRecognizer*)sender{
//    UILabel * label = sender.superclass;
    if (self.tabButton.selected) {
        float frameX = sender.view.frame.origin.x;
        float frameY = sender.view.frame.origin.y;
        float frameW = sender.view.frame.size.width;
        float frameH = sender.view.frame.size.height;
        float resultW = (frameX + frameW + 2) * SCREEN6P_SCALE;
        
        self.deleteBtn = [[UIButton alloc] init];
        [self.deleteBtn setImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
        [self.deleteBtn addTarget:self action:@selector(hiddenTabLabel:) forControlEvents:UIControlEventTouchUpInside];
        self.deleteBtn.frame = CGRectMake(resultW, frameY, frameH, frameH);
        self.deleteBtn.tag = self.tabLabelInImg.tag;
        if (self.editImageView.hidden) {
            [self.showImage addSubview:self.deleteBtn];
        }else{
            [self.editImageView addSubview:self.deleteBtn];
        }
    }else{
        return;
    }
    
}

- (void)hiddenTabLabel:(UIButton *)sender{
    
    sender.hidden = YES;
    self.tabLabelInImg.hidden = YES;
    
}

@end
